import json
import re
import requests
from requests.exceptions import RequestException
from multiprocessing import Pool


def get_one_page(url):
    headers = {"Content-Type": "application/x-www-form-urlencoded",
               "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/69.0.3497.100 Safari/537.36",
               "Referer": "http://sh,ke.com/ershoufang/"}
    try:
        response = requests.get(url, headers=headers)
        print(response.status_code)
        if response.status_code == 200:
            return response.text
        return response.text
    except RequestException:
        return None


def parse_one_page(html, offset):
    pattern = re.compile('<li class="clear">.*?href="(.*?)".*?'
                         + 'data-original="(.*?)".*?'
                         + 'alt="(.*?)".*?'
                         + '<div class="positionInfo">.*?<a.*?">(.*?)</a>.*?</div>.*?'
                         + '<div class="houseInfo">.*?<span class="houseIcon"></span>(.*?)</div>.*?'
                         + '<div class="followInfo">.*?<span class="starIcon"></span>(.*?)</div>.*?'
                         + '<div class="totalPrice"><span>(.*?)</span>.*?</div>.*?'
                         + 'data-price="(.*?)".*?'
                         + '</li>', re.S)

    items = re.findall(pattern, html)
    for item in items:

        yield {
            'page': 'pg' + str(offset),
            'link': item[0],
            'image': item[1],
            'des': item[2],
            'name': item[3],
            'info': item[4].replace("\n", "").replace(" ", ""),
            'follow': item[5].replace("\n", "").replace(" ", ""),
            'total': item[6],
            'price': item[7]
        }


def write_to_file(content):
    with open("sh_old_fang.txt", 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')
        f.close()


def main(offset):
    url = 'https://sh.ke.com/ershoufang/pg' + str(offset) + '/'
    html = get_one_page(url)
    for item in parse_one_page(html, offset):
        print(item)
        write_to_file(item)


if __name__ == '__main__':
    for i in range(2, 3):
        main(i)
    # pool = Pool(1)
    # pool.map(main, [i for i in range(2, 99)])